from urlparse import urlparse
import datetime
import re
import logging
import os
import urllib2

from google.appengine.ext.webapp import template
from google.appengine.ext import db

import model
import libs.pb64.converter as pb64

regexp = {
	"parseFullUrlWithSeconds" : "/([0-9]{14})([a-zA-Z]*)(?:/(.*))?",
	"parseFullUrl" : "/([0-9]{12})([a-zA-Z]*)(?:/(.*))?",
	"parseOldShortUrl" : "/s/([0-9]+)",
	"parseb64ShortUrl" : "/([a-zA-Z0-9]+)"
}

def prepareFormData():
	days = range(1, 32)		
	months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
	
	return {
		"days": days,
		"months": months
	}

def getContextRootFromUrl(url):
	o = urlparse(url)
	return o.scheme + "://" + o.netloc

def getNextCounter():
	counter = model.URLCounter.all().fetch(1)[0]
	next = counter.current
	counter.current += 1
	counter.put()
	return next

nbOfUrlsToRetrieve = 10

def processLatestAndPopularUrlQueries(q):
	qurls = q.fetch(nbOfUrlsToRetrieve)
	urls = []
	for u in qurls:
		parts = u.url.rsplit("/")
		if len(parts) == 5:
			time = parts[3]
			title = urllib2.unquote(parts[4])
			urls.append({
				"b64": pb64.encodeB64Padless(u.counter),
				"title": title + " (" + time + ")"
			})
	return urls

def getLatestUrls():
	q = db.GqlQuery("SELECT * FROM URLs order by counter desc limit " + str(nbOfUrlsToRetrieve))
	return processLatestAndPopularUrlQueries(q)

def getMostPopulars():
	q = db.GqlQuery("SELECT * FROM URLs order by nbOfTimesUsed desc limit " + str(nbOfUrlsToRetrieve))
	return processLatestAndPopularUrlQueries(q)

def getNbOfTotalUrls():
	count = 0
	try:
		count = model.URLCounter.all().fetch(1)[0].current
	except:
		count = 0
	return count
	
def storeUrl(url, target, options, title, customTheme, up):
	"""
	Checks if the URL was stored already, if not, stores it, then increments the usage counter
	"""
	
	# First add the trailing 00 if needed
	if len(target) == 12:
		target += "00"
	
	if options == None:
		options = ""
		
	fullUrl = getContextRootFromUrl(url) + "/" + target + options + "/" + title
	
	storedUrls = model.URLs.all().filter("url = ", fullUrl).fetch(1)
	if len(storedUrls) == 1:
		storedUrl = storedUrls[0]
	else:
		storedUrl = model.URLs(url = fullUrl, nbOfTimesUsed = 0, customTheme = customTheme)
		storedUrl.dateAdded = datetime.datetime.now()
		if up:
			storedUrl.up = True

	if storedUrl.counter == None:
		storedUrl.counter = getNextCounter()

	storedUrl.nbOfTimesUsed += 1
	storedUrl.put()
	
	return storedUrl

def isValidDate(dayStr, monthStr, yearStr, hourStr, minuteStr, secondStr):
	if 0 < int(dayStr) < 32 and 0 < int(monthStr) < 13 and -1 < int(hourStr) < 24 and -1 < int(minuteStr) < 60 and -1 < int(secondStr) < 60:
		return True
	else:
		return False

def getTemplateContent(tplPath, data):
	# Just comiles the template in fact
	# Also, at the same time, adds the static timestamp for browser cache reload
	fileObj = open("staticTs.txt", "r")
	ts = fileObj.read()
	fileObj.close()
	data["staticTs"] = ts
	return template.render(tplPath, data)